package com.jack.concurrency;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

/**
 * Created by zhang_j on 2019/12/5
 * CountDownLatch是一个工具类，可以理解为一个倒计时器
 */
public class MyCountDownLatch {
    private static final ThreadPoolExecutor EXECUTOR_SERVICE = new ThreadPoolExecutor(100,120,60,TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(1000),
            new ThreadFactoryBuilder().setNameFormat("mycountdownlatch-pool-%d").build(),
            new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(100);
        for(int i=0;i<100;i++){
            CountRunnable runnable = new CountRunnable(latch);
            EXECUTOR_SERVICE.execute(runnable);
        }
    }

    /**
     * 主线程开始执行…… ……
     * 等待两个线程执行完毕…… ……
     * 子线程：mycountdownlatch-pool-0执行
     * 子线程：mycountdownlatch-pool-1执行
     * 两个子线程都执行完毕，继续执行主线程
     * @param args
     */
//    public static void main(String[] args) {
//        CountDownLatch countDownLatch = new CountDownLatch(2);
//        System.out.println("主线程开始执行…… ……");
//        //第一个子线程执行
//        EXECUTOR_SERVICE.execute(()->{
//            try {
//                Thread.sleep(3000);
//                System.out.println("子线程："+Thread.currentThread().getName()+"执行");
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            countDownLatch.countDown();
//        });
//
//        //第二个子线程执行
//        EXECUTOR_SERVICE.execute(()->{
//            try {
//                Thread.sleep(3000);
//                System.out.println("子线程："+Thread.currentThread().getName()+"执行");
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            countDownLatch.countDown();
//        });
//
//        System.out.println("等待两个线程执行完毕…… ……");
//        try {
//            countDownLatch.await();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println("两个子线程都执行完毕，继续执行主线程");
//    }
}

class CountRunnable implements Runnable{
    private CountDownLatch latch ;
    public CountRunnable(CountDownLatch latch){
        this.latch = latch;
    }

    @Override
    public void run() {
        try{
            synchronized (latch){
                latch.countDown();
                System.out.println("thread counts = " + (latch.getCount()));
            }
            latch.await();
            System.out.println("concurrency counts = " + (100 - latch.getCount()));
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}